import asyncio
import socket
import time
import tkinter as tk
import ttkbootstrap as ttk

from src.recorder import Recorder
from src.translation_service import TranslationService
from src.broadcast import broadcast_translation, broadcast_recording_stopped
from src.log import SCRIPTP


FONT_FILE_NAME = 'AlimamaFangYuanTiVF-Thin-2.ttf'
FONT_FAMILY = '阿里妈妈方圆体 VF Medium'


class TranslationApp:
    def __init__(self, root, meeting_id):
        self.root = root
        self.meeting_id = meeting_id
        self.is_recording = False
        self.recorder = None
        self.translation_service = None
        self.selected_device_index = None

        style = ttk.Style()
        style.configure('primary.TButton', padding=(0, 6, 0, 8), foreground='#ffffff', background='#4080ff', borderwidth=0, font=(FONT_FAMILY, 12))
        style.configure('danger.TButton', padding=(0, 6, 0, 8), foreground='#ffffff', background='#F56C6C', borderwidth=0, font=(FONT_FAMILY, 12))
        style.configure('recoder.TLabel', foreground='#303133', font=(FONT_FAMILY, 12))
        style.configure('recoder.TCombobox', foreground='#606266', font=(FONT_FAMILY, 12))
        style.configure('norecoder.TLabel', foreground='#F56C6C', font=(FONT_FAMILY, 12))
        style.configure('recoder.TCheckbutton', foreground='#303133', font=(FONT_FAMILY, 12))
        
        self.setup_ui()
    
    def setup_ui(self):
        # 创建主框架
        main_frame = ttk.Frame(self.root)
        main_frame.pack(fill="both", expand=True, padx=20, pady=(20, 24))
        main_frame.columnconfigure(0, weight=1)
        main_frame.rowconfigure(0, weight=1)
        main_frame.rowconfigure(1, weight=1)
        main_frame.rowconfigure(2, weight=1)
        
        # 创建麦克风选择区域
        device_frame = ttk.Frame(main_frame)
        device_frame.grid(row=0, column=0)
        device_frame.columnconfigure(0, weight=1)
        device_frame.columnconfigure(1, weight=1)
        device_frame.columnconfigure(2, weight=1)
        device_frame.rowconfigure(0, weight=1)
        
        device_label = ttk.Label(device_frame, text="选择麦克风:", style="recoder.TLabel")
        device_label.grid(row=0, column=0, ipadx=20, padx=5)
        
        # 获取可用麦克风设备
        self.devices = Recorder.get_available_devices()
        
        if len(self.devices) > 0:
            # 有麦克风，显示选择下拉框
            device_names = [device["name"] for device in self.devices]
            self.device_var = tk.StringVar()
            self.device_var.set(device_names[0])  # 默认选择第一个设备
            
            self.device_combobox = ttk.Combobox(
                device_frame, 
                textvariable=self.device_var,
                values=device_names,
                state="readonly",
                width=30,
                style="recoder.TCombobox"
            )
            self.device_combobox.grid(row=0, column=1, columnspan=2, padx=5, sticky="EW")
        else:
            device_label = ttk.Label(device_frame, text="无可用麦克风", style="norecoder.TLabel")
            device_label.grid(row=0, column=1, columnspan=2, padx=5, sticky="EW")
        
        # 创建录音控制区域
        control_frame = ttk.Frame(main_frame)
        control_frame.grid(row=1, column=0, pady=(10, 10))
        control_frame.columnconfigure(0, weight=1)
        control_frame.columnconfigure(1, weight=1)
        control_frame.columnconfigure(2, weight=1)
        control_frame.rowconfigure(0, weight=1)
        control_frame.rowconfigure(1, weight=1)
        
        # 创建开始录音按钮
        self.start_button = ttk.Button(
            control_frame, 
            text="开始录音", 
            command=self.toggle_recording,
            bootstyle="primary", 
            width=20
        )
        self.start_button.grid(row=0, column=0, columnspan=2, padx=5, sticky="EW")
        
        # 创建保存录音复选框
        self.save_recording_var = tk.BooleanVar()
        self.save_recording_var.set(True)
        self.save_recording_checkbox = ttk.Checkbutton(
            control_frame, 
            text="保存录音", 
            variable=self.save_recording_var,
            style="recoder.TCheckbutton"
        )
        self.save_recording_checkbox.grid(row=0, column=2, ipadx=5, padx=10)

        langs_frame = ttk.Frame(main_frame)
        langs_frame.grid(row=2, column=0)
        langs_frame.columnconfigure(0, weight=1)
        langs_frame.columnconfigure(1, weight=1)
        langs_frame.columnconfigure(2, weight=1)
        langs_frame.columnconfigure(3, weight=1)
        langs_frame.rowconfigure(0, weight=1)

        self.lang_zh_var = tk.BooleanVar()
        self.lang_zh_var.set(True)
        self.lang_zh_checkbox = ttk.Checkbutton(
            langs_frame, 
            text="中文", 
            variable=self.lang_zh_var,
            style="recoder.TCheckbutton"
        )
        self.lang_zh_checkbox.grid(row=0, column=0, ipadx=5, padx=10)
        
        self.lang_en_var = tk.BooleanVar()
        self.lang_en_var.set(True)
        self.lang_en_checkbox = ttk.Checkbutton(
            langs_frame, 
            text="英文", 
            variable=self.lang_en_var,
            style="recoder.TCheckbutton"
        )
        self.lang_en_checkbox.grid(row=0, column=1, ipadx=5, padx=10)
        
        self.lang_ja_var = tk.BooleanVar()
        self.lang_ja_var.set(False)
        self.lang_ja_checkbox = ttk.Checkbutton(
            langs_frame, 
            text="日文", 
            variable=self.lang_ja_var,
            style="recoder.TCheckbutton"
        )
        self.lang_ja_checkbox.grid(row=0, column=2, ipadx=5, padx=10)
        
        self.lang_ko_var = tk.BooleanVar()
        self.lang_ko_var.set(False)
        self.lang_ko_checkbox = ttk.Checkbutton(
            langs_frame, 
            text="韩文", 
            variable=self.lang_ko_var,
            style="recoder.TCheckbutton"
        )
        self.lang_ko_checkbox.grid(row=0, column=3, ipadx=5, padx=10)
    
    def get_selected_device_index(self):
        """获取用户选择的麦克风设备索引"""
        if not hasattr(self, 'device_combobox'):
            # 没有下拉框，返回第一个设备索引或None
            return self.devices[0]["index"] if self.devices else None
        
        # 有下拉框，根据选择的名称查找索引
        selected_name = self.device_var.get()
        for device in self.devices:
            if device["name"] == selected_name:
                return device["index"]
        return None
    
    def get_selected_langs(self):
        """获取用户选择的翻译语言"""
        langs = []
        if self.lang_zh_var.get():
            langs.append("zh")
        if self.lang_en_var.get():
            langs.append("en")
        if self.lang_ja_var.get():
            langs.append("ja")
        if self.lang_ko_var.get():
            langs.append("ko")
        return langs

    def show_message(self, title, message):
        """显示一个允许复制内容的自定义对话框"""
        # 创建顶级窗口
        top = ttk.Toplevel(title=title, iconphoto=str(SCRIPTP.joinpath("logo.png")), resizable=(False, False), topmost=True, alpha=0)
        top.geometry("480x200")
        
        # 设置窗口样式
        style = ttk.Style()
        style.configure("TLabel", font=(FONT_FAMILY, 12))
        style.configure("TButton", padding=(0, 6, 0, 8), font=(FONT_FAMILY, 12))
        
        # 创建主框架
        main_frame = ttk.Frame(top, padding=20)
        main_frame.pack(fill="both", expand=True)
        
        # 创建消息标签
        message_label = ttk.Label(main_frame, text=message, wraplength=430, justify="left")
        message_label.pack(pady=10, anchor="n")
        
        # 提取消息中的链接部分
        url = message.split(": ")[-1] if ": " in message else message
        
        # 创建复制按钮
        def copy_to_clipboard():
            # 清空剪贴板
            top.clipboard_clear()
            # 将链接复制到剪贴板
            top.clipboard_append(url)
            # 显示复制成功提示
            copy_button.configure(text="已复制!")
            copy_button.configure(bootstyle="success")
            # 1秒后恢复按钮状态
            top.after(1000, lambda: top.destroy())
        
        copy_button = ttk.Button(main_frame, text="复制", command=copy_to_clipboard, bootstyle="primary")
        copy_button.place(relx=0.9, rely=0.85, relwidth=0.2, anchor="center")
        
        # 创建关闭按钮
        close_button = ttk.Button(main_frame, text="关闭", command=top.destroy, bootstyle="secondary")
        close_button.place(relx=0.65, rely=0.85, relwidth=0.2, anchor="center")
        
        def fade_in():
            top.place_window_center()
            top.attributes("-alpha", 1)

        top.after(200, fade_in)
        # 设置窗口模式为模态，阻止用户操作主窗口
        top.grab_set()
    
    def toggle_recording(self):
        if not self.is_recording:
            # 开始录音
            try:
                self.is_recording = True
                self.start_button.configure(text="停止录音", bootstyle="danger")

                self.device_combobox.config(state="disabled")
                self.save_recording_checkbox.config(state="disabled")
                
                # 获取选择的设备索引
                self.selected_device_index = self.get_selected_device_index()
                
                # 显示自定义提示框，允许复制网址
                ip_address = socket.gethostbyname(socket.gethostname())
                self.meeting_id = str(time.time()).split(".")[0]
                url = f"http://{ip_address}:9507/meeting?id={self.meeting_id}"
                self.show_message("提示", f"您可以通过访问以下链接来获取实时翻译内容: {url}")

                SCRIPTP.joinpath("meeting_id").write_text(self.meeting_id)
                
                # 初始化翻译服务和录音
                self.translation_service = TranslationService(
                    self.meeting_id, 
                    langs=self.get_selected_langs(),
                    on_translation=broadcast_translation
                )
                self.recorder = Recorder(
                    self.translation_service, 
                    self.selected_device_index, 
                    save_recording=self.save_recording_var.get()
                )
                self.recorder.start_recording()
            except Exception as e:
                print(f"开始录音失败: {e}")
                self.is_recording = False
                self.start_button.configure(text="开始录音", bootstyle="primary")
                self.device_combobox.config(state="normal")
                self.save_recording_checkbox.config(state="normal")
        else:
            # 停止录音
            self.toggle_stop_recording()

    def toggle_stop_recording(self):
        if self.is_recording:
            try:
                self.is_recording = False
                self.start_button.configure(text="开始录音", bootstyle="primary")
                self.start_button.config(state="disabled")

                self.device_combobox.config(state="normal")
                self.save_recording_checkbox.config(state="normal")
                
                # 广播停止录音通知
                try:
                    # 尝试在当前线程的事件循环中运行
                    loop = asyncio.get_running_loop()
                    loop.create_task(broadcast_recording_stopped(self.meeting_id))
                except RuntimeError:
                    # 当前线程没有事件循环，创建一个新的事件循环
                    loop = asyncio.new_event_loop()
                    asyncio.set_event_loop(loop)
                    loop.run_until_complete(broadcast_recording_stopped(self.meeting_id))
                
                if self.recorder:
                    self.recorder.stop_recording()
                    self.recorder = None
                
                if self.translation_service:
                    self.translation_service.stop()
                    self.translation_service = None
                
                SCRIPTP.joinpath("meeting_id").write_text("")
                self.start_button.config(state="normal")

            except Exception as e:
                print(f"停止录音失败: {e}")